package com.tarena.dao;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;

import com.tarena.domain.Product;
import com.tarena.util.HbnUtil;

public class ProductDao {

	/**
	 * @InsertProduct
	 * @param product
	 */
	public void InsertProduct(Product product) {
		Session s = HbnUtil.getSession();
		try {
			s.beginTransaction();
			s.save(product);
			s.getTransaction().commit();
		} catch (HibernateException e) {
			s.getTransaction().rollback();
			e.printStackTrace();
		}
		s.close();
	}

	/**
	 * @delete Product
	 * @param productId
	 * @description becuse user
	 */
	public void deleteProductsById(int[] productId) {
		Session s = HbnUtil.getSession();
		try {
			s.beginTransaction();
			for (int i=0; i<productId.length; i++) {
				Product p = new Product();
				p.setId(productId[i]);
				s.delete(p);
//				s.delete(s.get(Product.class, productId[i]));
				//万一没有这个ID，就会抛异常
			}
			s.getTransaction().commit();
		} catch (HibernateException e) {
			s.getTransaction().rollback();
		} finally {
			s.close();
		}
	}

	/**
	 * @Get product
	 * @return list
	 */
	public List<Product> getProduct() {
		Session s = HbnUtil.getSession();
		Query query = s.createQuery("from Product");
		List<Product> productList = query.list();
		return productList;
	}
	
	/**
	 * @update a product
	 * @param product
	 */
	public void updateProduct(Product product) {
		Session s = HbnUtil.getSession();
		try {
			s.beginTransaction();

			s.getTransaction().commit();

		} catch (HibernateException e) {
			e.printStackTrace();
			s.getTransaction().rollback();
		} finally {
			s.close();
		}
	}
		
}
